package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.UserDao;
import entity.User;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");


        String username = req.getParameter("username");
        String password = req.getParameter("password");

        System.out.println("username:"+username);
        System.out.println("password:"+password);

        Map<String ,Object> return_map = new HashMap<>();

        UserDao userDao = new UserDao();

        User registerUser = new User();
        registerUser.setUsername(username);
        registerUser.setPassword(password);
        String ages = req.getParameter("age");
        int age = Integer.parseInt(ages);
        String gender = req.getParameter("gender");
        String email = req.getParameter("email");

       /* LoginService loginService = new LoginService();
        User user = loginService.login(loginUser);*/

        User user = userDao.login(registerUser);

        if(user == null) {
            //用户不存在
            return_map.put("msg", Boolean.valueOf(true));
        }else {
            //用户存在，注册失败
            return_map.put("msg", Boolean.valueOf(false));
        }

        User registerUser1 = new User();
        registerUser.setUsername(username);
        registerUser.setPassword(password);
        registerUser.setAge(age);
        registerUser.setGender(gender);
        registerUser.setEmail(email);
        userDao.register(registerUser1);

        ObjectMapper mapper = new ObjectMapper();
        //利用Jackson将map转化为json对象，
        // writer 将转换后的json字符串保存到字符输出流中，最后给客户端
        mapper.writeValue(resp.getWriter(),return_map);



    }
}
